<template>
  <div class="main">
    <topHeader :title="$t('agv.title')"></topHeader>
    <div class="h-2"></div>
    <div class="d-flex flex-row h-90">
      <div class="agvMachine-list--wrap bg-custom w-30 m-2">
        <!-- <div class="shade_box" ></div> -->
        <table class="table-wrap table1">
          <thead class="work_status--header">
            <tr>
              <th>{{ $t('agv.filedname1') }}</th>
              <th>{{ $t('agv.filedname2') }}</th>
              <th>{{ $t('agv.filedname3') }}</th>
              <th>{{ $t('agv.filedname4') }}</th>
            </tr>
          </thead>
          <tbody class="w-100 work_status--content"
            :style="agvMachineList.length > 15 ? 'animation-duration: ' + duration + 's' : ''">
            <tr v-for="(item, index) in agvMachineList" :key="index" :class="stateAgv(item.stateId)">
              <td>{{ item.name }}</td>
              <td>{{ item.state }}</td>
              <td class="w-30">-----</td>
              <td :style="{color:energy(item.batteryPercentile)}">{{ item.batteryPercentile }}%</td>
            </tr>
          </tbody>
        </table>
      </div>

      <div class="w-70">
        <div class="w-100 h-100">
          <div id="myDiagramDiv" style="width: 100%; height: 100%;
                        position: relative; -webkit-tap-highlight-color: rgba(255, 255, 255, 0); ">
            <canvas tabindex="0" width="1808" height="1196" style=" position:
                            absolute; top: 0px; left: 0px; z-index: 2; user-select: none; width: 904px; height: 598px;
                            ">This text is displayed if your browser does not support the Canvas HTML
              element.</canvas>
            <div style=" position: absolute; overflow: auto; width: 904px; height: 598px; z-index: 1;
                            ">
              <div style="position: absolute; width: 1px; height: 1px"></div>
            </div>
          </div>
        </div>
        <!-- http://192.168.10.81:4333 admin|AGV_Board 123456-->
        <!-- <div class="w-100 h-100 my-iframe">
          <iframe src="http://192.168.12.20:4333" ref="iframes" style="width: 100%;height: 100%;" frameborder="no" border="0"  id="agviframe" ></iframe>

        </div> -->
      </div>

    </div>
  </div>
</template>

<script setup lang="ts">
import topHeader from '@/components/topHeader/index.vue'
import go from 'gojs'
import bg from '@/assets/img/workshop.png'
import agv from '@/assets/img/agv.png'
import { getAGV } from '@/service/api/index'

const { proxy } = getCurrentInstance() as any
const agvMachineList = ref<{
  batteryPercentile: number,
  name: string,
  state: string,
  stateId:number
}[]>([])
const timer: any = reactive({
  timeData: 0,
  timerData: null,
  intervalData: 10000
})
const duration = ref(0)
const getScreenWidth: any = computed(() => proxy.$common.getScreenWidth())
const random = (min: number, max: number) => {
  return proxy.$common.random(min, max)
}
// let $ = go.GraphObject.make;
let myDiagram: any = null;
const init = () => {
  var $ = go.GraphObject.make;
  myDiagram = $(go.Diagram, "myDiagramDiv", {
    "toolManager.mouseWheelBehavior": go.ToolManager.WheelZoom, // 开启鼠标滚轮缩放
    initialContentAlignment: go.Spot.Center, //画布位置
    isReadOnly: true, //只读
    // scale: 1.4 * (getScreenWidth.value/1920), //根据屏幕设置初始视图大小比例
    "toolManager.hoverDelay": 100 
  });
  //添加并设置背景
  myDiagram.add(
    $(
      go.Part,
      {
        // width: 1031,
        // height: 568,
        width:524,
        height:485,
        layerName: "Background",
        position: new go.Point(-10.66, -6.99),
        selectable: false,
        pickable: false,
        // scale:0.05,
      },
     
      $(go.Picture, { source: ' http://192.168.12.20:4333/static/maps/46dd1225-d1cc-4ac8-8e83-aa872f0fe35f/kyzh00001.png' })
      // $(go.Picture, { source: 'http://192.168.12.20:4333/static/maps/49d391a8-96bb-46a4-97d7-f7cb4195f308/KyTest.png' })
    )
  );

  // 每个agv小车的模板
  myDiagram.nodeTemplate = $(
    go.Node,
    new go.Binding("location", "loc"),
    new go.AnimationTrigger("position", { duration: 2000 }),
    { locationSpot: go.Spot.Left },
    $(go.Picture, { source: agv, width: 40, height: 50 }, new go.Binding("flip", "flip")),
    $(
      go.Panel,
      "Vertical",
      { background: 'rgba(0,0,0,0.5)', position: new go.Point(40, -50), },
      $(go.TextBlock, { margin: 3, stroke: 'white' }, new go.Binding("text", "key", function (val: string) {
        return "AGV编号：" + val
      })),
      $(go.TextBlock, { margin: 3, stroke: 'white' }, new go.Binding("text", "loc", function (val: string) {
        return "坐标：" + val
      })),
      $(go.TextBlock, { margin: 3, stroke: 'white' }, new go.Binding("text", "status", function (val: string) {
        return "状态：" + val
      }))
    ),
    {
      toolTip: $(
        "ToolTip", $(
          go.Panel,
          "Vertical",
          $(go.TextBlock, { margin: 3 }, new go.Binding("text", "key", function (val: string) {
            return "AGV编号：" + val
          })),
          $(go.TextBlock, { margin: 3 }, new go.Binding("text", "loc", function (val: string) {
            return "坐标：" + val
          })),
          $(go.TextBlock, { margin: 3 }, new go.Binding("text", "status", function (val: string) {
            return "状态：" + val
          })))
      ), // end Adornment
    }
  );

  const simpletemplate =
    $(go.Part, "Vertical",
      new go.Binding("position", "loc"),
      $(go.Shape, { width: 50, fill: "lightgreen", height: 40, alignment: go.Spot.Top }),
    )

  const templmap = new go.Map();
  templmap.add("simple", simpletemplate);
  templmap.add("", myDiagram.nodeTemplate);

  myDiagram.nodeTemplateMap = templmap;

  // flip:让小车自动旋转 FlipHorizontal（水平反转） 、FlipVertical（垂直翻转） 、FlipBoth（水平垂直反转） 、None
  myDiagram.model.nodeDataArray = [
    { key: "#3031", src: "60x90", loc: new go.Point(18, 153), color: 6, flip: go.GraphObject.none, status: '运行中' },
    { key: "#3032", src: "80x50", loc: new go.Point(140, 250), color: 8, flip: go.GraphObject.none, status: '运行中' },
  ];


  // 模拟实时监控位置
  function randomMovement() {
    var model = myDiagram.model;
    model.startTransaction("update locations");
    var arr = model.nodeDataArray.filter((item: any) => !(item.category == 'simple'));;

    var picture = myDiagram.parts.first();
    for (var i = 0; i < arr.length; i++) {
      var data = arr[i];
      var pt = data.loc;
      var x = Math.trunc(pt.x + 25 * Math.random() - 10);
      var y = Math.trunc(pt.y + 25 * Math.random() - 10);
      // make sure the kittens stay inside the house
      var b = picture.actualBounds;
      if (x > 68 && x < 480 && y > 313) return
      if (x < b.x || x > b.right) x = pt.x;
      if (y < b.y || y > b.bottom) y = pt.y;
      model.setDataProperty(data, "loc", new go.Point(x, y));
    }
    model.commitTransaction("update locations");
  }

  function animationRack() {

    myDiagram.parts.each(function (node: any) {
      if (node.category == 'simple') {
      }
    })
  }
  //随机位置
  function looprandomMovement() {
    var timer = setTimeout(function () {
      clearTimeout(timer)
      randomMovement();
      looprandomMovement();
    }, 2000);

  }
  function looprank() {
    var timer = setTimeout(function () {
      clearTimeout(timer)
      animationRack();
      looprank();
    }, 1000);
  }
  looprandomMovement(); // start the simulation
  looprank(); // start the simulation
  // generate some colors based on hue value

  //以下是随机rgb颜色
  function makeFill(number: number) {
    return HSVtoRGB(0.1 * number, 0.5, 0.7);
  }
  function makeStroke(number: number) {
    return HSVtoRGB(0.1 * number, 0.5, 0.5); // same color but darker (less V in HSV)
  }
  function HSVtoRGB(h: any, s: any, v: any) {
    var r, g, b, i, f, p, q, t;
    i = Math.floor(h * 6);
    f = h * 6 - i;
    p = v * (1 - s);
    q = v * (1 - f * s);
    t = v * (1 - (1 - f) * s);
    switch (i % 6) {
      case 0:
        (r = v), (g = t), (b = p);
        break;
      case 1:
        (r = q), (g = v), (b = p);
        break;
      case 2:
        (r = p), (g = v), (b = t);
        break;
      case 3:
        (r = p), (g = q), (b = v);
        break;
      case 4:
        (r = t), (g = p), (b = v);
        break;
      case 5:
        (r = v), (g = p), (b = q);
        break;
    }
    return (
      "rgb(" +
      Math.floor(r * 255) +
      "," +
      Math.floor(g * 255) +
      "," +
      Math.floor(b * 255) +
      ")"
    );
  }
};
const getData = async () => {
  let res: any = await getAGV()
  agvMachineList.value = res.data
}
const realTimeFresh = async () => {
  let currTimeData = new Date().getTime()
  if ((currTimeData - timer.timeData) > timer.intervalData || timer.timeData === 0) {
    timer.timeData = new Date().getTime()
    getData()
  }
  timer.timerData = requestAnimationFrame(realTimeFresh)
}
const stateAgv = (state: number) => {
  if ([6, 7, 8].includes(state)) { // 异常
    return 'red_highlight'
  }
}
const energy = (num:number)=>{
  if(num>=80){
    return '#3CB371'
  }else if(num>=40){
    return '#FFD700'
  }else{
    return '#B22222'
  }
}
onMounted(async () => {
  init();
  // realTimeFresh()
})
onUnmounted(() => {
  cancelAnimationFrame(timer.timerData)
})
</script>

<style  scoped>
.agvMachine-list--wrap {
  position: relative;
  color: white;
  overflow: hidden;
}

.shade_box {
  height: 20px;
  z-index: 111;
  position: absolute;
  left: 0;
  top: 0px;
  right: 0;
}

.status-desc--list {
  margin-top: 1.5%;
}

.status-desc--item {
  margin-right: 3vh;
}

.status-desc--color {
  width: 16px;
  height: 16px;
  display: block;
  margin-right: .5vh;
}

.status-desc--val {
  color: #fff;
  line-height: 14px;
}

.work_status--header th,
.work_status--content td {
  padding: 1rem 0;
  text-align: center;
}

.work_status--header tr {
  background: #0a2a2c;
}

.work_status--content tr {
  background-color: #233b3e;
}

.table-wrap {
  border-collapse: separate;
  width: 100%;
  overflow: hidde;
  word-wrap: break-word;
  border-spacing: 0 1.2rem;
  padding: 0 1rem;
}

.red_highlight {
  animation: red_highlight_bg 1.5s linear infinite;
}
@keyframes red_highlight_bg {
  0% {
    box-shadow: 0 0 0 0 rgb(197, 42, 1);
  }

  50% {
    box-shadow: 0 0 0 5px rgba(197, 42, 0.3);
  }

  100% {
    box-shadow: 0 0 0 0 rgba(197, 42, 0);
  }
}

</style>